<template>
	<view>
		<u-loading-page :loading="true"></u-loading-page>
	</view>
</template>

<script setup>
import apis from '@/apis'
import axios from '@/apis/request'
import { useAuthStore } from '@/stores/auth'
import { sleep } from '@/utils/tool'
import { onLoad } from '@dcloudio/uni-app'
import qs from 'qs'

onLoad(() => {
	login()
})

async function login() {
	const { setOpenId, setToken, setUserInfo } = useAuthStore()
	// #ifdef H5
	const params = qs.parse(location.search.substring(1))
	console.log('params', params)
	if (params.code) {
		// TODO 这里写h5微信登录逻辑
	} else {
		uni.reLaunch({ url: '/pages/template/Form' })
		// const params = {
		// 	appid: '',
		// 	redirect_uri: '',
		// 	response_type: 'code',
		// 	scope: 'snsapi_base',
		// 	state: 'STATE'
		// }
		// window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?${qs.stringify(params)}#wechat_redirect`
	}
	// #endif
	// #ifdef MP-WEIXIN
	try {
		const data = await uni.login({
			provider: 'weixin'
		})
		axios
			.post(apis.common.wxLogin, {
				code: data.code
			})
			.then(res => {
				if (res.openId && !res.token) {
					setOpenId(res.openId)
					uni.reLaunch({ url: '/pages/login/Login' })
				} else {
					setToken(res.token)
					setUserInfo(res.user)
					uni.reLaunch({
						url: '/pages/index/Index'
					})
				}
			})
			.catch(error => {
				console.log('进入了错误 :>> ', error)
				uni.reLaunch({ url: '/pages/template/Form' })
			})
	} catch (error) {
		uni.showToast({
			title: '自动登录失败，请重新登录',
			icon: 'error'
		})
		await sleep(2000)
		uni.reLaunch({ url: '/pages/login/Login' })
	}
	// #endif
}
</script>

<style lang="scss" scoped></style>
